﻿/*
 *  Get data from http://www.hanyang.ac.kr/rss/notice.html
 *      and parse it!
 */
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.IO;
using System.IO.IsolatedStorage;
using System.Diagnostics;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Linq;


namespace SmartHYU_TestVersion.Notice
{
    /*************************************************
     * 
     *       Class for Download and Store Notice RSS
     *      
     * 
     ***************************************************/
    public class HyuNotice
    {
        /********************************************************************************
         *      Constants                                                               *
         ********************************************************************************/
        //private const string rssUrl = "http://www.hanyang.ac.kr/rss/notice.html";
        //private const string rssUrl = "http://mobile.hanyang.ac.kr/api/hynotice.php";
        private const string rssUrl = "http://icewall.hanyang.ac.kr/hyum/hynotice.php";
        private const string rssFileName = "hyuNotice.rss";


        /********************************************************************************
         *      Properties                                                              *
         ********************************************************************************/
        public string Title     { get; set; }
        public string Author    { get; set; }
        public string Category  { get; set; }
        public string Url       { get; set; }

        protected string rawXml {get;set;}

        /********************************************************************************
         *      Public Methods                                                          *
         ********************************************************************************/
        public bool GetRssDataFromWebAndStore() 
        {
            WebClient rssDownloader = new WebClient();
            rssDownloader.DownloadStringAsync(new Uri(rssUrl));

            // When download completed, save RSS file to local storage
            rssDownloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(rssDownloader_DownloadStringCompleted);
            
            return true;
        }

        public List<HyuNoticeForm> LoadNoticeFromLocalStorage()
        {
            List<HyuNoticeForm> Notices = new List<HyuNoticeForm>();

            // load local data + exception handling
            if (!loadRawXmlFromLocalStorage()) 
            {
                return new List<HyuNoticeForm>() { new HyuNoticeForm() { Title = "Loading", Author = "Please Wait..", Url = "http://icewall.hanyang.ac.kr/smarthyu" } };
            }

            // empty file?
            if (this.rawXml == "")
                return new List<HyuNoticeForm>() { 
                    new HyuNoticeForm() {
                        Title = "Temporary Not in Service", Author = "Smart HYU 7", Url = "http://icewall.hanyang.ac.kr/smarthyu/" 
                    }
                };

            XDocument noticeRssParer = XDocument.Parse(this.rawXml);
            var tempNotices = (from noticeElements in noticeRssParer.Descendants("item")
                                          select new HyuNoticeForm 
                                          { 
                                              Title = noticeElements.Element("title").Value.Trim(),
                                              Author = noticeElements.Element("author").Value,
                                              Url = noticeElements.Element("link").Value
                                          }).Take(20);

            foreach (var tempNotice in tempNotices)
            {
                Notices.Add(new HyuNoticeForm()
                {
                    Title = tempNotice.Title,
                    Author = tempNotice.Author,
                    Url = tempNotice.Url
                });
            }

            // return Notices (Only Top 20 Notices)
            return Notices;
        }


        /********************************************************************************
         *      Private Methods                                                         *
         ********************************************************************************/
        private void rssDownloader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // If not in connection..
            if (e.Error != null) {
                // Do nothing
                return;
            }
            
            using (IsolatedStorageFile noticeStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Truncate file if exists
                if (noticeStorage.FileExists(rssFileName))
                    noticeStorage.DeleteFile(rssFileName);

                // Create File Stream!
                IsolatedStorageFileStream noticeStorageStream = 
                    new IsolatedStorageFileStream(rssFileName, FileMode.OpenOrCreate, noticeStorage);
                StreamWriter rssWriter = new StreamWriter(noticeStorageStream);

                
                // writes it!
                try                     
                {
                    rssWriter.Write(e.Result); 
                }
                // Exception Handling
                catch (Exception ex)    
                { 
                    MessageBox.Show("Exception has occured while writing notice XML : " + ex.Message.ToString()); 
                    Debug.WriteLine(ex.Message.ToString()); 
                }

                // Closing..
                rssWriter.Close();
                noticeStorageStream.Close();
            }

            // Generates Event
            onDownloadNoticeCompleted();
        }

        // load RSS data from local storage and returns it to this.rawXML
        //      if there is no data in local storage - return false
        private bool loadRawXmlFromLocalStorage()
        {
            using (IsolatedStorageFile noticeStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
            {
                // check file exists
                if (!noticeStorage.FileExists(rssFileName))
                {
                    GetRssDataFromWebAndStore();
                    MessageBox.Show("Please wait until download completed");
                    return false;
                    // waiting for download and save
                    // while (!noticeStorage.FileExists(rssFileName)) ;
                }

                IsolatedStorageFileStream noticeStorageStream = new IsolatedStorageFileStream(rssFileName, FileMode.Open, noticeStorage);
                StreamReader noticeReader = new StreamReader(noticeStorageStream);

                try
                {
                    this.rawXml = noticeReader.ReadToEnd();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception has occured while reading notice XML : " + ex.Message.ToString());
                    Debug.WriteLine(ex.Message.ToString()); 
                }

                noticeReader.Close();
                noticeStorageStream.Close();
            }

            return true;

        }


        /********************************************************************************
         *      User Defined Event                                                      *
         ********************************************************************************/
        public delegate void DownloadNoticeStatus(bool completeStatus, string noticeXml);
        public event DownloadNoticeStatus DownloadNoticeCompleted;
        protected void onDownloadNoticeCompleted() { DownloadNoticeCompleted(true, this.rawXml); }
    }

    public class HyuNoticeForm
    {
        public string Title     { get; set; }
        public string Author    { get; set; }
        public string Url       { get; set; }
    }
}
